package DP1;



/**
 * 反转链表
 */
public class Main15 {
    public static void main(String[] args) {
        ListNode head = new ListNode(3);
        head.next = new ListNode(1);
        head.next.next = new ListNode(9);
        head.next.next.next = new ListNode(5);
        head.show();
        System.out.println();
        ReverseList1(head).show();
    }

    public static ListNode ReverseList(ListNode head){
        ListNode pre = head;
        ListNode cur = null;
        while(pre!=null){
            ListNode temp = pre.next;
            pre.next = cur;
            cur = pre;
            pre = temp;
        }
        return cur;
    }

    public static ListNode ReverseList1(ListNode head){
        if(head == null || head.next == null) return head;
        ListNode res = ReverseList(head.next);
        head.next.next = head;
        head.next = null;
        return res;
    }


}



class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }

    void show(){
        ListNode head = this;
        while(head!=null){
            System.out.print(head.val + " ");
            head = head.next;
        }

    }

}